package com.visikard.ui.fragment;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.app.FragmentManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.visikard.application.Constant;
import com.visikard.application.UIMessage;
import com.visikard.business.GoogleGeoAPIBUS;
import com.visikard.item.ItemPlaceGoogle;
import com.visikard.request.ParseRequesUtils;
import com.visikard.ui.R;
import com.visikard.ui.activity.CouponBuilderActivityV3;
import com.visikard.ui.fragment.MyDatePickerDialog.SelectDateCallback;
import com.visikard.utility.Utils;

public class CouponInfoFragment extends BaseFragment implements SelectDateCallback {
	// setArguments-->onAttach-->onCreate-->onCreateView-->onActivityCreated
	// onDestroyView-->onDestroy-->onDetach

	public static final int MSG_SEARCH_DONE = 1000;
	public static final int MSG_ERROR = 1001;
	public static final int MSG_GOT_LOCATION = 1002;

	private CouponBuilderActivityV3 me;

	private View mView;
	private EditText mEditText_cpname, mEditText_cppercent, mEditText_cpmax, mEditText_cpwriteup;
	private AutoCompleteTextView mEditText_location;
	private TextView mTextView_start_month, mTextView_start_day, mTextView_start_year;
	private TextView mTextView_end_month, mTextView_end_day, mTextView_end_year;
	private Button mButton_next, mButton_back;
	private SelectDateCallback mCallback;

	ArrayList<GeoSearchItem> listCity = new ArrayList<GeoSearchItem>();
	ArrayList<GeoSearchItem> cachedList = new ArrayList<GeoSearchItem>();
	AsyncTask<Void, Void, Void> mInitTask;
	AsyncTask<Void, Void, Void> mSearchTask;
	ArrayAdapter<GeoSearchItem> adapter;
	SearchLocationTask searchLocationTask;
	GetDetailLocationTask getDetailLocationTask;
	ItemPlaceGoogle item;

	private void initControls(View view) {
		mEditText_cpname = (EditText) view.findViewById(R.id.coupon_name);
		mEditText_cppercent = (EditText) view.findViewById(R.id.coupon_percent);
		mEditText_cpmax = (EditText) view.findViewById(R.id.coupon_maxoff);
		mEditText_cpwriteup = (EditText) view.findViewById(R.id.write_up_to);

		mEditText_location = (AutoCompleteTextView) view.findViewById(R.id.participating_locations);

		mTextView_start_month = (TextView) view.findViewById(R.id.start_date_month);
		mTextView_start_day = (TextView) view.findViewById(R.id.start_date_day);
		mTextView_start_year = (TextView) view.findViewById(R.id.start_date_year);

		mTextView_end_month = (TextView) view.findViewById(R.id.end_date_month);
		mTextView_end_day = (TextView) view.findViewById(R.id.end_date_day);
		mTextView_end_year = (TextView) view.findViewById(R.id.end_date_year);

		mButton_next = (Button) view.findViewById(R.id.btn_next);
		mButton_back = (Button) view.findViewById(R.id.btn_back);

		mEditText_location.setOnClickListener(new MyOnClickListenner());

		mTextView_start_month.setOnClickListener(new MyOnClickListenner());
		mTextView_start_day.setOnClickListener(new MyOnClickListenner());
		mTextView_start_year.setOnClickListener(new MyOnClickListenner());

		mTextView_end_month.setOnClickListener(new MyOnClickListenner());
		mTextView_end_day.setOnClickListener(new MyOnClickListenner());
		mTextView_end_year.setOnClickListener(new MyOnClickListenner());

		mButton_next.setOnClickListener(new MyOnClickListenner());
		mButton_back.setOnClickListener(new MyOnClickListenner());

		mEditText_location.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable s) {
				String kw = s.toString();
				if (mEditText_location.isPerformingCompletion() || (kw.trim().length() <= 0))
					return;
				if (searchLocationTask != null) {
					searchLocationTask.cancel(true);
				}

				kw = kw.replace(" ", "%20");
				searchLocationTask = new SearchLocationTask(kw, false);
				if (Utils.hasHoneycomb()) {
					searchLocationTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
				}
				else
					searchLocationTask.execute();
			}
		});

		mEditText_location.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int index, long arg3) {
				GeoSearchItem selectedItem = listCity.get(index);
				if (getDetailLocationTask != null) {
					getDetailLocationTask.cancel(true);
				}
				getDetailLocationTask = new GetDetailLocationTask(selectedItem.ref);
				if (Utils.hasHoneycomb()) {
					getDetailLocationTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
				}
				else {
					getDetailLocationTask.execute();
				}
			}
		});
	}

	@SuppressWarnings("unchecked")
	@Override
	protected boolean handleMessage(Message msg) {
		switch (msg.what) {
			case MSG_SEARCH_DONE:
				mHandler.sendEmptyMessage(UIMessage.MSG_DISMISS_DIALOG);
				mHandler.removeMessages(MSG_SEARCH_DONE);
				try {
					ArrayList<GeoSearchItem> result = (ArrayList<GeoSearchItem>) msg.obj;
					if (result != null && !result.isEmpty()) {
						listCity.clear();
						listCity.addAll(result);
						adapter = new ArrayAdapter<GeoSearchItem>(me, R.layout.set_location_simple_list_item, listCity);
						adapter.setNotifyOnChange(true);
						mEditText_location.setAdapter(adapter);
					}
					mEditText_location.showDropDown();
				}
				catch (Exception e) {
					e.printStackTrace();
				}
				return false;

			case MSG_GOT_LOCATION:
				mHandler.sendEmptyMessage(UIMessage.MSG_DISMISS_DIALOG);
				return false;

			case MSG_ERROR:
				mHandler.sendEmptyMessage(UIMessage.MSG_DISMISS_DIALOG);
				return false;

			default:
				return super.handleMessage(msg);
		}
	}

	@Override
	public void setArguments(Bundle args) {
		// TODO Auto-generated method stub
		super.setArguments(args);
	}

	@Override
	public void onAttach(Activity activity) {
		// TODO Auto-generated method stub
		super.onAttach(activity);
		try {

			mCallback = this;
		}
		catch (ClassCastException e) {
			throw new ClassCastException(activity.toString());
		}
	}

	@Override
	public void onCreate(Bundle arg0) {
		// TODO Auto-generated method stub
		super.onCreate(arg0);
		me = (CouponBuilderActivityV3) getActivity();

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		mView = inflater.inflate(R.layout.coupon_information_activity, null);
		initControls(mView);
		return mView;

	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		listCity = new ArrayList<CouponInfoFragment.GeoSearchItem>();
		adapter = new ArrayAdapter<GeoSearchItem>(me, R.layout.set_location_simple_list_item, listCity);
		adapter.setNotifyOnChange(true);
		mEditText_location.setAdapter(adapter);
	}

	private class MyOnClickListenner implements OnClickListener {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			if (v == mEditText_location) {

			}
			else if (v == mTextView_start_day || v == mTextView_start_month || v == mTextView_start_year) {
				MyDatePickerDialog datepicker = new MyDatePickerDialog(mCallback, 1);
				datepicker.show(getFragmentManager(), "datepickerdialog");
			}
			else if (v == mTextView_end_day || v == mTextView_end_month || v == mTextView_end_year) {
				MyDatePickerDialog datepicker = new MyDatePickerDialog(mCallback, 2);
				datepicker.show(getFragmentManager(), "datepickerdialog");
			}
			else if (v == mButton_back) {
				FragmentManager fm = getActivity().getSupportFragmentManager();
				fm.popBackStack();
			}
			else if (v == mButton_next) {
				if (validateData()) {

					CouponPreviewFragment couponPreviewFragment = (CouponPreviewFragment) getFragmentManager()
							.findFragmentByTag(Constant.COUPON_PREVIEW_FRAGMENT_TAG);
					if (couponPreviewFragment == null) {
						couponPreviewFragment = new CouponPreviewFragment();
					}
					Bundle bundle = new Bundle();
					String cpName = mEditText_cpname.getText().toString().trim();
					String cpPercent = mEditText_cppercent.getText().toString().trim();
					String cpMax = mEditText_cpmax.getText().toString().trim();
					String cpDes = mEditText_cpwriteup.getText().toString().trim();
					String address = mEditText_location.getText().toString().trim();
					String startDate = mTextView_start_month.getText().toString().trim() + "/"
							+ mTextView_start_day.getText().toString().trim() + "/"
							+ mTextView_start_year.getText().toString().trim();

					String endDate = mTextView_end_month.getText().toString().trim() + "/"
							+ mTextView_end_day.getText().toString().trim() + "/"
							+ mTextView_end_year.getText().toString().trim();

					bundle.putString("name", cpName);
					bundle.putString("percent", cpPercent);
					bundle.putString("cpmax", cpMax);
					bundle.putString("des", cpDes);
					bundle.putString("address", address);
					bundle.putString("sdate", startDate);
					bundle.putString("edate", endDate);
					bundle.putString("lat", item.getLatitude());
					bundle.putString("lon", item.getLongitude());

					couponPreviewFragment.setArguments(bundle);
					Utils.toFragment(getFragmentManager(), couponPreviewFragment, Constant.COUPON_PREVIEW_FRAGMENT_TAG,
							R.id.framelayout_coupon_builder);

				}

			}
		}
	}

	private boolean validateData() {
		boolean result = false;
		if (mEditText_cpname.getText().toString().trim().equals("")) {
			Utils.showToast(me,
					String.format(me.getString(R.string.alert_empty), mEditText_cpname.getHint().toString()), 0);

		}

		else if (mTextView_start_month.getText().toString().equals(me.getString(R.string.txt_month))) {
			Utils.showToast(me, String.format(me.getString(R.string.alert_empty), "Start Date"), 0);
		}
		else if (mTextView_end_month.getText().toString().equals(me.getString(R.string.txt_month))) {
			Utils.showToast(me, String.format(me.getString(R.string.alert_empty), "End Date"), 0);
		}
		else if (mEditText_location.getText().toString().equals("")) {
			Utils.showToast(me,
					String.format(me.getString(R.string.alert_empty), me.getString(R.string.participating_locations)),
					0);
		}

		else {
			Calendar calendar = Calendar.getInstance();
			calendar.set(Calendar.YEAR, Integer.parseInt(mTextView_start_year.getText().toString()));
			calendar.set(Calendar.MONTH, Integer.parseInt(mTextView_start_month.getText().toString()));
			calendar.set(Calendar.DATE, Integer.parseInt(mTextView_start_day.getText().toString()));
			Date start = calendar.getTime();

			calendar.set(Calendar.YEAR, Integer.parseInt(mTextView_end_year.getText().toString()));
			calendar.set(Calendar.MONTH, Integer.parseInt(mTextView_end_month.getText().toString()));
			calendar.set(Calendar.DATE, Integer.parseInt(mTextView_end_day.getText().toString()));
			Date end = calendar.getTime();
			if (end.compareTo(start) < 0) {
				Utils.showToast(me, me.getString(R.string.alert_enddate_startdate), 0);

			}
			else {
				return true;
			}

		}

		return result;
	}

	@Override
	public void onSelectDateCallback(int day, int month, int year, int StartOrEnd) {
		// TODO Auto-generated method stub

		if (StartOrEnd == 1) {
			mTextView_start_day.setText(String.valueOf(day));
			mTextView_start_month.setText(String.valueOf(month));
			mTextView_start_year.setText(String.valueOf(year));
		}
		if (StartOrEnd == 2) {
			mTextView_end_day.setText(String.valueOf(day));
			mTextView_end_month.setText(String.valueOf(month));
			mTextView_end_year.setText(String.valueOf(year));
		}
	}

	class SearchLocationTask extends AsyncTask<Void, Void, ArrayList<GeoSearchItem>> {
		String keyWord = "";

		public SearchLocationTask(String kw, boolean isShowProgress) {
			keyWord = kw;
			if (isShowProgress)
				mHandler.sendEmptyMessage(UIMessage.MSG_SHOW_DIALOG);
		}

		@Override
		protected ArrayList<GeoSearchItem> doInBackground(Void... params) {
			int i;
			String searchString = new String();
			ArrayList<GeoSearchItem> result = new ArrayList<CouponInfoFragment.GeoSearchItem>();
			try {
				searchString = GoogleGeoAPIBUS.doSearchAutoComplete(keyWord);
				JSONArray jArray = (new JSONObject(searchString)).getJSONArray("predictions");
				for (i = 0; i < jArray.length(); i++) {
					JSONObject o = jArray.getJSONObject(i);
					GeoSearchItem item = new GeoSearchItem(o);
					if (!isCancelled()) {
						result.add(item);
					}
					else {
						result.clear();
						break;
					}
				}

			}
			catch (Exception e) {
				return null;
			}
			return result;
		}

		@Override
		protected void onPostExecute(ArrayList<GeoSearchItem> result) {
			super.onPostExecute(result);
			if (!isCancelled() && result != null && !result.isEmpty()) {
				Message msg = mHandler.obtainMessage(MSG_SEARCH_DONE, result);
				mHandler.sendMessage(msg);
			}
		}
	}

	class GetDetailLocationTask extends AsyncTask<Void, Void, ItemPlaceGoogle> {
		private String referrence;

		public GetDetailLocationTask(String ref) {
			referrence = ref;
			mHandler.sendEmptyMessage(UIMessage.MSG_SHOW_DIALOG);
		}

		@Override
		protected ItemPlaceGoogle doInBackground(Void... params) {
			String searchString;
			try {
				searchString = GoogleGeoAPIBUS.getDetailPlaceByRef(referrence);
				JSONObject result = (new JSONObject(searchString)).getJSONObject("result");
				if (result != null) {
					item = ParseRequesUtils.parseGooglePlaceAPI(result);
					item.setFormattedAddress(mEditText_location.getText().toString());
					if (!isCancelled())
						mHandler.sendEmptyMessage(MSG_GOT_LOCATION);
				}
			}
			catch (Exception e) {
				mHandler.sendEmptyMessage(MSG_ERROR);
			}
			return null;
		}
	}

	static class GeoSearchItem {
		String id;
		String des;
		String ref;

		public GeoSearchItem() {
		}

		public GeoSearchItem(JSONObject obj) {
			id = obj.optString("id");
			des = obj.optString("description");
			ref = obj.optString("reference");
		}

		@Override
		public String toString() {
			return des;
		}
	}

}
